/**
 * Created by admin on 2016/8/9.
 */
var assert = require('../assert');

//获取对应商品的评论
exports.getComments = function (req, res) {
    var productId = req.params.productId;
    var isCount = req.query.isCount;
    if (!productId || productId == 'undefined'){
        res.send(assert.response_sms(400, '参数有误'));
        return
    }
    // 分页的初始化参数
    var page = 1;
    var limit = 10;
    // 判断page是否合法
    if (req.query.page){
        try {
            page = parseInt(req.query.page);
        }catch (error){
            page = 1;
        }
    }

    var Product = Parse.Object.extend('OPProduct');
    var product = new Product();
    product.id = productId;
    var query =new Parse.Query('OPProductComment');
    query.equalTo('product', product);
    if(!isCount){
        var skip = (page-1) * limit;
        query.skip(skip);
        query.limit(limit);
        query.include('user');
        query.select('createdAt', 'content', 'score', 'objectId', 'user','images');
    }
    if(isCount){
        query.count().then(function (countInfo){
            if(countInfo){
                res.send(assert.response_sms(200,'获取数量成功', countInfo))
            }else{
                res.send(assert.response_sms(200,'没有评论', 0))
            }
        })
    }else{
        query.find().then(function (results) {
            if (results.length<1){
                res.send(assert.response_sms(200,'没有更多评论了', results));
            }else {
                var response_content = [];
                for (var i=0,len = results.length; i<len; i++){
                    var temp = assert.obj2dic(results[i],['content', 'score', 'objectId', 'user','images']);
                    temp['createdAt'] = results[i].get('createdAt').Format('yyyy-MM-dd hh:mm');
                    temp.avatar = temp.user.get('avatar');
                    if(!temp['avatar']){
                        temp['avatar'] = 'AppIcon512.png'
                    }
                    response_content.push(temp);
                }
                res.send(assert.response_sms(200,'获取评论成功', response_content));
            }
        }, function (error) {
            res.send(assert.response_sms(400, '获取评论失败' + error,message))
        });
    }
};
// 添加商品评论
exports.postComment = function (req, res) {
    // 获取参数
    var userId = req.body.userId;
    var productId = req.params.productId;
    var content = req.body.content;
    var score = req.body.score;
    score = parseInt(score);
    var images = req.body.images;
    var orderProductId = req.body.orderProductId;
    var orderId = req.body.orderId;
    var hasNull = assert.check_parms([userId, productId, content, score, orderProductId, orderId]);

    if (hasNull){
        res.send(assert.response_sms(400, 'userId, produceId, content, score, orderProductId,orderId中有空值'));
        return
    }
    // 声明类
    var OPProductComment = Parse.Object.extend('OPProductComment');
    var Product = Parse.Object.extend('OPProduct');
    var User = Parse.Object.extend('User');
    // 创建对象
    var productComment = new OPProductComment();
    var user = new User();
    var product = new Product();
    var query = new Parse.Query('OPOrderProduct');
    // 赋值
    user.id = userId;
    product.id = productId;
    productComment.set('user', user);
    productComment.set('product', product);
    productComment.set('content', content);
    productComment.set('score', score);
    productComment.set('product', product);
    if(images){
        productComment.set('images',JSON.parse(images));
    }
    // 保存对象
    productComment.save().then(function (result) {
        query.get(orderProductId).then(function (orderProduct) {
            orderProduct.set('comment', result);
            orderProduct.save().then(function (result) {
                res.send(assert.response_sms(200, '添加成功'));
                checkOrderStatus(orderId);
            },function (error) {
                res.send(assert.response_sms(401, 'orderProduct绑定comment失败'));
            })
        }, function (error) {
            res.send(assert.response_sms(402, '查找orderProduct失败'));
        });
    }, function (error) {
        res.send(assert.response_sms(403, '保存comment失败'));
    })
};
// 去检查这个order的所有上平是否都已经评价过了，如果都评价过了就改变订单状态
function checkOrderStatus(orderId) {
    var query = new Parse.Query('OPOrder');
    query.include('orderProducts');
    query.get(orderId).then(function (order) {
        var orderProducts = order.get('orderProducts');
        for (var i=0, len = orderProducts.length; i<len; i++){
            if (typeof (orderProducts[i].get('comment')) == 'undefined'){
                return;
            }
        }
        order.set('status', 4);
        order.save().then(function (result) {
            console.log('order评价完成');
        }, function (error) {
            console.log('订单设置为完成失败', error);
        });
    }, function (error) {
        console.log('查找订单出错')
    });
}